﻿using Application;
using Application.Interfaces.Repository;
using Domain.Core;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Mapping;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Linq;

namespace Infrastructure.Implementations.Repository.EntityFramework
{
    public class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
        static EfRepository()
        {
            //using (var context = AppEngine.Container.GetInstance<DbContext>())
            //{
            //    var objectContext = ((IObjectContextAdapter)context).ObjectContext;
            //    var mappingCollection = (StorageMappingItemCollection)objectContext.MetadataWorkspace.GetItemCollection(DataSpace.CSSpace);
            //    mappingCollection.GenerateViews(new List<EdmSchemaError>());
            //}
        }

        private readonly DbContext _context;
        private IDbSet<T> _entities;

        public EfRepository(DbContext context)
        {
            this._context = context;
            this._entities = context.Set<T>();
        }

        public T FindById(int id)
        {
            return this._entities.Find(id);
        }

        public IQueryable<T> FindAsNoTracking()
        {
            return this._entities.AsNoTracking();
        }

        public IQueryable<T> Find()
        {
            return this._entities;
        }

        public void Add(T entity)
        {
            this._entities.Add(entity);
        }

        public void Remove(T entity)
        {
            this._entities.Remove(entity);
        }

        public int SaveChanges()
        {
            return this._context.SaveChanges();
        }
    }
}